<template>
  <div class="card shadow uploader-popup" v-if="items.length">
    <div class="card-header bg-dark py-3">
      <div class="d-flex justify-content-between align-items-center">
        <span class="text-light">{{ uploadingStatus }}</span>
        <PopupControls @toggle="showPopupBody = !showPopupBody" @close="handleClose" />
      </div>
    </div>
    <div class="upload-items" v-show="showPopupBody">
      <ul class="list-group list-group-flush">
        <UploadItem
          v-for="item in items"
          :key="item.id"
          :item="item"
          @change="handleItemChange"
          @handleSelectChange="$emit('handleSelectChange', $event)" />
      </ul>
    </div>
  </div>
</template>

<script setup>
import { watch, computed, ref } from 'vue'
import PopupControls from './PopupControls.vue'
import UploadItem from '../item/UploadItem.vue'
import states from '../states'

const items = ref([])

const showPopupBody = ref(true)

watch(
  () => props.files,
  (newFiles) => {
    items.value.unshift(...getUploadItems(newFiles))
  }
)

// 数据重构
const getUploadItems = (files) => {
  return Array.from(files).map((file) => ({
    id: randomId,
    file,
    progress: 0,
    state: states.WAITING,
    response: null,
  }))
}

const randomId = () => {
  return Math.random().toString(36).substring(2, 9)
}

// 计算当前上传图片的个数
const uploadingItemsCount = computed(() => {
  return items.value.filter(
    (item) => item.state === states.WAITING || item.state === states.UPLOADING
  ).length
})

const uploadingStatus = computed(() => {
  return `正在上传${uploadingItemsCount.value}个文件`
})

const handleClose = () => {
  if (confirm('关闭将取消所有上传中的文件?')) {
    items.value.splice(0)
  }
}
const emits = defineEmits(['update-complete'])
const handleItemChange = (item) => {
  if (item.state === '上传完成') {
    emits('update-complete', item.response)
  }
}

const props = defineProps({
  files: {
    type: Object,
    required: true,
  },
})
</script>

<style scoped>
.uploader-popup {
  width: 400px;
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 999;
}
</style>
